if(typeof Promise == "undefined") alert("您的浏览器不支持promise异步计算");



function pointInPoly(point, polygon) {
	var x = point[0], y = point[1];

	var inside = false;
	for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
		var xi = polygon[i][0], yi = polygon[i][1];
		var xj = polygon[j][0], yj = polygon[j][1];

		var intersect = ((yi > y) !== (yj > y)) &&
			(x < (xj - xi) * (y - yi) / (yj - yi) + xi);
		if (intersect) {
			inside = !inside;
		}
	}
	return inside;
}

var geoInfo = [];
var regionList = [];

function convertGeoInfo(geoJSON){
  var geoList = [];
  geoJSON.forEach(function(item,index){
    let geoItem = {};
    geoItem.region = item.properties.region;
    geoItem.cd = item.geometry.coordinates[0];
    geoList.push(geoItem);
  })
  return geoList;
}

moveDirList = [
      {"en":"NW","cn":"西北","dir":315}
      ,{"en":"WNW","cn":"西北西","dir":292.5}
      ,{"en":"WLY","cn":"偏西","dir":270}
      ,{"en":"NNW","cn":"北北西","dir":337.5}
      ,{"en":"NLY","cn":"偏北","dir":360}
      ,{"en":"NNE","cn":"北北东","dir":22.5}
      ,{"en":"NE","cn":"东北","dir":45}
      ,{"en":"ENE","cn":"东北东","dir":67.5}
      ,{"en":"WSW","cn":"西南西","dir":247.5}
      ,{"en":"SW","cn":"西南","dir":225}
      ,{"en":"ELY","cn":"偏东","dir":90}
      ,{"en":"SLY","cn":"偏南","dir":180}
      ,{"en":"SE","cn":"东南","dir":135}
      ,{"en":"ESE","cn":"东南东","dir":112.5}
      ,{"en":"SSW","cn":"南南西","dir":202.5}
      ,{"en":"SSE","cn":"南南东","dir":157.5}      
      ,{"en":"ALMOST STATIONARY","cn":"原地摆动","dir":999}  
    ];


function converDir(dir){
  var dirCN = ''
  if(dir!=NaN){
    if(dir<=11.25) return '偏北';
    for(let i=0;i<moveDirList.length;i++){
      if(Math.abs(dir - moveDirList[i].dir)<=11.25){
        dirCN = moveDirList[i].cn;
        break;
      }
    }
    return dirCN;
    
  }
  else{
    return dirCN;
  }



}


function converData(list){
  var finalList = [];
  list.forEach(function(item,index){
    finalList[index] = {
      "ID":item.TCID
      ,"rankEN":item.TCRANK
      ,"lat":Number(item.LATITUDE)
      ,"lon":Number(item.LONGITUDE)
      ,"pressure":item.PRESSURE
      ,"rankEN":item.TCRANK
      ,"uyear":item.DDATETIME.slice(0,4)
      ,"umonth":item.DDATETIME.slice(5,7)
      ,"uday":item.DDATETIME.slice(8,10)
      ,"uhour":item.DDATETIME.slice(11,13)
      ,"speedKMH":Number(item.SPEED)
      ,"moveDir":item.DIRECTION.length?converDir(Number(item.DIRECTION)):""
      ,"direction":item.DIRECTION
      ,"TSID":item.TSID
    };
    let localTime = new Date(Number(finalList[index].uyear), Number(finalList[index].umonth) - 1,
     Number(finalList[index].uday), Number(finalList[index].uhour) + 8);
    finalList[index].month = localTime.getMonth()+1;
    finalList[index].date = localTime.getDate();
    finalList[index].hour = localTime.getHours();
    finalList[index].speedKTS = Math.round(finalList[index].speedKMH/1.852);

  });

  return finalList;

}

function fitTyphoon(tyList,tyInfo){
  tyList.forEach(function(itemL,indexL){
    tyInfo.forEach(function(itemI,indexI){
      if(itemL.TSID == itemI.TSID){
        itemL.TSCNAME = itemI.TSCNAME;
        itemL.TSENAME = itemI.TSENAME;
      }
    })
  })
}


Vue.component('tc-info', {
  template: '\
  <div class="list">\
  <a title="删除" class="button" v-on:click="$emit(\'remove\')">✖</a>\
  <div class="list01">\
  <span>当地时间<input v-model="date">日\
  <input v-model="hour">时</span>\
  <span>TC级别<select v-bind:title="rankEN" v-model="rankEN">\
  <option v-for="rank in rankList" v-bind:value="rank.en">{{rank.cn}}</option>\
  </select></span>\
  <span>编号<input v-bind:title="rid" v-model="ID"></span>\
  <span>中心气压<input v-model="pressure">hPa</span>\
  </div>\
  <div class="list02">\
  <span>纬度<input v-model="lat">N</span>\
  <span>经度<input v-model="lon">E</span>\
  <span>位置<select v-model="locationCN">\
  <option v-for="loc in region" v-bind:value="loc.cn">{{loc.cn}}</option>\
  </select></span>\
  <span>location<select v-model="locationEN">\
  <option v-for="loc in region" v-bind:value="loc.en">{{loc.en}}</option>\
  </select></span></div>\
  <div class="list03">\
  <span>强度趋势<select v-model="trend">\
  <option v-for="item in trendList" v-bind:value="item.cn">{{item.cn}}</option>\
  </select></span>\
  <span>移向<select v-model="moveDir">\
  <option v-for="item in dirList" v-bind:value="item.cn">{{item.cn}}</option>\
  </select></span>\
  <span>移速<input v-model="speedKMH">公里/小时</span>\
  <span>speed<input v-model="speedKTS">KTS</span>\
  </div>\
  <div class="messageBox">\
  <textarea name="messageEN" v-model="depictEN"></textarea>\
  </div>\
  <div class="messageBox">\
  <textarea name="messageCN" v-model="depictCN"></textarea>\
  </div>\
  </div>\
  ',

  props:{'tcItem':Object
    ,'rankList':Array
    ,'region':Array
    ,'trendList':Array
    ,'dirList':Array
  },

  data: function(){
    
    console.log(regionList);
    var inside = false;
    var location = null;
    _this = this;
    for(let i=0;i<geoInfo.length;i++){
      inside = pointInPoly([this.tcItem.lon,this.tcItem.lat],geoInfo[i].cd);
      if(inside){
        location = geoInfo[i].region;
          //console.log(location);
          break;
        } 
      }

      var locEN = null;
      if(inside){
        regionList.forEach(function(item){
        if(location == item.cn){
          locEN = item.en;
        } 
      });
      }
      
      
    return {
      date:this.tcItem.date?this.tcItem.date:""
      ,hour:this.tcItem.hour?this.tcItem.hour:""
      ,rankEN:this.tcItem.rankEN?this.tcItem.rankEN:""
      ,ID:this.tcItem.ID?this.tcItem.ID:""
      ,pressure:this.tcItem.pressure?this.tcItem.pressure:""
      ,lat:this.tcItem.lat?this.tcItem.lat:""
      ,lon:this.tcItem.lon?this.tcItem.lon:""
      ,locationCN:location?location:""
      ,locationEN:locEN?locEN:""
      ,trend:this.tcItem.trend?this.tcItem.trend:""
      ,moveDir:this.tcItem.moveDir?this.tcItem.moveDir:""
      ,speedKMH:this.tcItem.speedKMH?this.tcItem.speedKMH:""
      ,speedKTS:this.tcItem.speedKTS?this.tcItem.speedKTS:""
      ,rid:this.tcItem.rid?this.tcItem.rid:0.1
      //,oldCN:""
    }
  }

  ,computed:{
    rankCN:function(){
      let _rankEN = this.rankEN;
      let rank = 'error';
      this.rankList.forEach(
        function(item){
          if(_rankEN == item.en ){
            rank = item.cn;
          } 
        }
      )     
      if(rank !='error') return rank;
    }
    ,moveDirEN:function(){
      let _dir = this.moveDir;
      let dirEN = 'error';
      this.dirList.forEach(
        function(item){
          if(_dir == item.cn ){
            dirEN = item.en;
          } 
        }
      )
      if(dirEN !='error') return dirEN;
    }

    ,depictEN:function(){
      let text = (this.date?'AT '+ this.date +'/':'') 
      + (this.hour?(this.hour + ':00' +' L.T.'):'')
      + (this.rankEN?' THE '+ this.rankEN:'')
      + (this.ID? '('+this.ID+')':'')
    	+ (this.pressure?' ' + this.pressure + 'hPa':'')
      + (this.locationEN?' OVER '+'THE ' + this.locationEN:'')
      + (this.lat?' WAS LOCATED NEAR ' + this.lat + 'N ':'')
      + (this.lon?this.lon +'E. ':'')
    	+ (this.moveDirEN?'THE MOVEMENT IS ' + this.moveDirEN :'')
      + (this.speedKTS?' ' + this.speedKTS +'KTS.':'');
      return text;
    }

    ,depictCN:function(){
      let text = (this.date?this.date +'日' :'')
      + (this.hour?this.hour + '时(北京时)，' :'')
      + (this.rankCN?this.rankCN:'')
      + (this.ID? '（编号：'+this.ID+'）':'')
    	+ (this.lat?'位于北纬' + this.lat + '度':'')
      + (this.lon?'，东经' + this.lon +'度':'')
      + (this.pressure?'，中心气压' + this.pressure + '百帕，':'')
    	+ (this.locationCN?'也就是在' + this.locationCN:'')
    	+ (this.moveDir?'，向' + this.moveDir + '方向移动':'')
      + (this.speedKMH?'，移速' + this.speedKMH +'公里/小时。':'');
      return text;
    }

  }

  ,watch:{//改成computed属性更好？
    locationEN:function(){
      //console.log("locationEN");
      let loc = 'error';
      let _EN = this.locationEN;
      this.region.forEach(function(item){
        if(_EN == item.en) loc = item.cn;
      });
      if(loc != 'error') this.locationCN = loc;
      
    }

    ,locationCN:function(){
      let loc = 'error';
      let _CN = this.locationCN;
      this.region.forEach(function(item){
        if(_CN == item.cn){
          loc = item.en;
        } 
      });
      if(loc != 'error') this.locationEN = loc;
    }

    
    ,lat:function(){
      this.pnpoly([this.lon,this.lat]);      
    }
    ,lon:function(){
      this.pnpoly([this.lon,this.lat]);
      
    }
  }
  ,methods:{
    pnpoly:function(point){
      let inside = false;
      let location = "";
      _this = this;
      for(let i=0;i<geoInfo.length;i++){
        
        inside = pointInPoly(point,geoInfo[i].cd);
        if(inside){
          location = geoInfo[i].region;
          //console.log(location);
          break;
        } 
      }
      if(inside) this.locationCN = location;      
    }
    ,changeLocation:function(){
      let loc = null;
      let _CN = this.locationCN;
      this.region.forEach(function(item){
        if(_CN == item.cn){
          loc = item.en;
        } 
      });
      if(loc != null) this.locationEN = loc;
    }
  }
 /* ,mounted:function(){
    var _this = this;
    //this.$nextTick(function(){
    var inside = false;
    var location = null;
    for(let i=0;i<geoInfo.length;i++){
      inside = pointInPoly([this.tcItem.lon,this.tcItem.lat],geoInfo[i].cd);
      if(inside){
        _this.locationCN = geoInfo[i].region;
          //console.log(_this.locationCN);
          break;
        } 
      }

      var locEN = null;
      if(inside){
        regionList.forEach(function(item){
          if(location == item.cn){
            _this.locationEN = item.en;
          } 
        });
      }
  }
    */
})

var app = new Vue({
	el:'#app'
	,data:{
    TClist : []
    ,TCRankList:[]
    ,region:[]
    ,trendList : []
    ,moveDirList:[]
    ,remoteList:[]
    ,startTime:"20160828"
    ,endTime:"20160830"
    ,TCinfo : []
	}
  ,created:function(){
    //this.$nextTick(function(){
      this.getBasicInfo();
    //}) 
  }
  ,mounted:function(){
    _this = this;
    this.$nextTick(function(){

    }) 
  }

	,filters:{

	}
	,computed:{

	}
  ,methods: {
    getBasicInfo:function(){
      var _this = this;

      axios.get('resource/typhoonInfo.json')
        .then(function (res) {
          //console.log(res);
          regionList = res.data.result.region;
          _this.TCRankList = res.data.result.TCRankList;
          _this.region = res.data.result.region;
          
          _this.trendList = res.data.result.trendList;
          _this.moveDirList = res.data.result.moveDirList;
                ///////////测试用////
          axios.get('resource/TCList.json')
           .then(function (res) {
          //console.log(res);
          res.data.result.TClist.forEach(function(item){
            item.rid = Math.random()*10;
          })
            _this.TClist = res.data.result.TClist;
          })
         .catch(function (error) {
            console.log(error);
         });
//////////////测试用结束///////////
//业务用可链接数据库后启用//      this.getData();
        })
         .catch(function (error) {
            console.log(error);
      });

      axios.get('resource/map.geo.json')
        .then(function (res) {
          //console.log(res);
            geoInfo = convertGeoInfo(res.data["features"]);
        })
         .catch(function (error) {
            console.log(error);
      });


    }

    

    ,addNewItem:function(TC){
      //this.TClist.splice(1, 0, {});
      //var rid = Math.random()*10;
      //this.TClist.push({"rid":rid});
      var rid = Math.random()*10;
      if(TC){
        TC.rid = rid;
        this.TClist.unshift(TC);
      }
      else{
        this.TClist.unshift({"rid":rid});
      }
      
    }
////////////////////////////////
    ,getData:function(){
      var params = 'startTime=' + this.startTime + '&' +
                   'endTime=' + this.endTime;
      
      var fullURL = 'http://10.148.36.55:2333/getData?' + params + '&interface=getObs';
      _this = this;
      axios.get(fullURL)
        .then(function (res) {
          //console.log(res);
          _this.remoteList = converData(res.data.DATA);
          //console.log(_this.removeList);
          params = params + '&interface=getInfo';
          let url =  'http://10.148.36.55:2333/getData?' + params;
          axios.get(url)
            .then(function (res) {
              //console.log(res);
              //_this.remoteList = 
              _this.fitTyphoon(res.data.DATA);
            })

            .catch(function (error) {
              console.log(error);
            });
        })
         .catch(function (error) {
            console.log(error);
         });
    }

    ,fitTyphoon:function(tyInfo){
      var tyList = this.remoteList;
      tyList.forEach(function(itemL){
        tyInfo.forEach(function(itemI){
          if(itemL.TSID == itemI.TSID){
            Vue.set(itemL,"TSCNAME",itemI.TSCNAME);
            Vue.set(itemL,"TSENAME",itemI.TSENAME);
            //itemL.TSCNAME = itemI.TSCNAME;
            //itemL.TSENAME = itemI.TSENAME;
            }
          })
        })
    }

  }
  ,watch:{
    
  }
});

//AT 01/14:00 L.T.THE LOW PRESSURE AREA 1006HPA OVER THE PACIFIC OCEAN EAST OF PHILIPPINES WAS LOCATED NEAR 4N 138E.THE MOVEMENT IS WLY 5KTS.
//01日14时(北京)，低压区，位于北纬4度，东经138度，中心气压1006百帕，也就是在菲律宾以东的太平洋洋面，缓慢西移。